package belajarzk.action.maintenance;

import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.sys.ExecutionsCtrl;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Include;
import org.zkoss.zul.Menubar;
import org.zkoss.zul.Menuitem;
import org.zkoss.zul.Menupopup;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import belajarzk.action.master.helper.ChangePasswordWindow;
import belajarzk.common.Common;
import belajarzk.database.hibernate.HibernateUtil;
import belajarzk.database.model.Menu;
import belajarzk.database.model.Tbmrole;
import belajarzk.database.model.Tbmuser;


public class MainAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2446397351568124278L;

	private Menubar menubar;
	private Include iframe;

	private ChangePasswordWindow changePasswordWindow;

	// private String county = Common.locale.getCountry();

	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		if (session.getAttribute("usersTemp") == null) {
			execution.sendRedirect("../login.zul");
			return;
		}
		loadTree();
	}

	private synchronized Boolean hasChild(Integer root, Set<Menu> menus) {
		for (Menu menu : menus) {
			if (menu.getRoot().equals(root)) {
				return true;
			}
		}
		return false;
	}

	private void createRootSubMenu(final Include iframe, Integer root,
			Set<Menu> menus, Menupopup componen) {
		iframe.setProgressing(true);
		for (final Menu menu : menus) {
			if (menu.getRoot().equals(root)) {
				Boolean ada = hasChild(menu.getChild(), menus);
				if (ada) {
					// org.zkoss.zul.Menu menuitem = new org.zkoss.zul.Menu(menu
					// .getLabel(), menu.getUrl());
					Tbmuser tbmuser = Common.getCurrentUser();
					String county = tbmuser.getBahasa();
					org.zkoss.zul.Menu menuitem = new org.zkoss.zul.Menu(
							(county.equals(Common.locale.getCountry()) ? menu
									.getLabelId() : menu.getLabel()), menu
									.getUrl());

					// menuitem.setImage("/img/z-bullet3.gif");
					menuitem.setParent(componen);
					Menupopup menupopup = new Menupopup();
					menupopup.setParent(menuitem);
					createRootSubMenu(iframe, menu.getChild(), menus, menupopup);

				} else {
					// Menuitem menuitem = new Menuitem(menu.getLabel(), menu
					// .getUrl());
					Tbmuser tbmuser = Common.getCurrentUser();
					String county = tbmuser.getBahasa();
					Menuitem menuitem = new Menuitem((county
							.equals(Common.locale.getCountry()) ? menu
							.getLabelId() : menu.getLabel()), menu.getUrl());
					// menuitem.setImage("/img/z-bullet3.gif");
					menuitem.setParent(componen);

					menuitem.addEventListener("onClick", new EventListener() {
						public void onEvent(Event event) throws Exception {
							if (menu.getUrl().trim().equals("rubah_password")) {
								changePasswordWindow.setClosable(false);
								changePasswordWindow.setVisible(true);
								changePasswordWindow.onModal();
							} else if (menu.getUrl().trim().endsWith(
									"login.zul")) {
								Executions.getCurrent().sendRedirect(
										menu.getUrl().trim());
							} else {
								iframe
										.setSrc(menu.getUrl() == null
												|| menu.getUrl().trim().equals(
														"") ? "blank.zul"
												: menu.getUrl().trim());
							}
						}
					});
				}
			}
		}

	}

	public void createTreeMenu(final Include iframe, Menubar menubar,
			Tbmrole job) {
		final Set<Menu> menus = job.getMenus();

		if (menus == null || menus.size() == 0) {
			session.setAttribute("users", null);
			session.setAttribute("usersTemp", null);
			execution.sendRedirect("../login.zul");
			return;
		}

		for (final Menu menu : menus) {
			if (menu.getRoot().equals(0)) {

				Boolean ada = hasChild(menu.getChild(), menus);
				if (ada) {
					Tbmuser tbmuser = Common.getCurrentUser();
					String county = tbmuser.getBahasa();
					org.zkoss.zul.Menu menuitem = new org.zkoss.zul.Menu(
							(county.equals(Common.locale.getCountry()) ? menu
									.getLabelId() : menu.getLabel()), menu
									.getUrl());

					// org.zkoss.zul.Menu menuitem = new org.zkoss.zul.Menu(menu
					// .getLabel());
					menuitem.setParent(menubar);
					Menupopup menupopup = new Menupopup();
					createRootSubMenu(iframe, menu.getChild(), menus, menupopup);
					menupopup.setParent(menuitem);
				} else {
					Tbmuser tbmuser = Common.getCurrentUser();
					String county = tbmuser.getBahasa();
					org.zkoss.zul.Menuitem menuitem = new org.zkoss.zul.Menuitem(
							(county.equals(Common.locale.getCountry()) ? menu
									.getLabelId() : menu.getLabel()), menu
									.getUrl());

					// org.zkoss.zul.Menuitem menuitem = new
					// org.zkoss.zul.Menuitem(
					// menu.getLabel());
					menuitem.setParent(menubar);
					menuitem.addEventListener("onClick", new EventListener() {
						public void onEvent(Event event) throws Exception {
							// System.out.println("Sip banget");
							if (menu.getUrl() != null
									&& menu.getUrl().trim().endsWith(
											"login.zul")) {
								Messagebox.show("Are you sure want to logout ?", "Warning",
										Messagebox.YES, "/img/help.gif",
										new EventListener() {

											@Override
											public void onEvent(Event event)
													throws Exception {
												int i = new Integer(event
														.getData().toString());
												if (i == 0)
													return;

												Executions
														.getCurrent()
														.sendRedirect(
																menu.getUrl()
																		.trim());

											}
										});

							} else {
								iframe
										.setSrc(menu.getUrl() == null
												|| menu.getUrl().trim().equals(
														"") ? "blank.zul"
												: menu.getUrl().trim());
							}
						}
					});
				}
			}
		}
	}

	public void loadTree() {

		Tbmuser users = (Tbmuser) Sessions.getCurrent().getAttribute(
				"usersTemp");
		if (users == null || users.getUserRole() == null
				|| users.getUserRole().getMenus() == null)
			return;

		Session ses = HibernateUtil.currentSession();

		Criteria criteria = ses.createCriteria(Tbmuser.class);
		criteria.add(Restrictions.idEq(users.getUserId()));
		users = ((Tbmuser) criteria.uniqueResult());
		Sessions.getCurrent().setAttribute("users", users);
		createTreeMenu(iframe, menubar, users.getUserRole());

		org.zkoss.zul.Menuitem menuitem = new org.zkoss.zul.Menuitem("Help",
				"bantuan");

		menuitem.setParent(menubar);
		menuitem.addEventListener("onClick", new EventListener() {
			@SuppressWarnings("deprecation")
			public void onEvent(Event event) throws Exception {
				Window window = ((Window) ExecutionsCtrl.getCurrentCtrl()
						.getCurrentPage().getVariable("bantuan"));
				/*window.setVisible(true);
				window.onModal();*/
			}
		});

		menuitem = new org.zkoss.zul.Menuitem("Logout", "../login.zul");
		menuitem.setParent(menubar);
		menuitem.addEventListener("onClick", new EventListener() {
			public void onEvent(Event event) throws Exception {
				// System.out.println("Sip banget");

				Messagebox.show("Are you sure want to logout ?", "Question", Messagebox.OK
						| Messagebox.CANCEL, Messagebox.EXCLAMATION,
						new EventListener() {

							@Override
							public void onEvent(Event event) throws Exception {
								int i = new Integer(event.getData().toString());
								System.out
										.println("i = " + i
												+ "  Messagebox.OK =  "
												+ Messagebox.OK);
								if (i == Messagebox.CANCEL)
									return;

								if (i == Messagebox.OK) {
									Executions.getCurrent().sendRedirect(
											"../login.zul");
								}

							}
						});

			}
		});

		ses.clear();

	}

}
